<template>
  <section class="fault-library-detail" v-loading="loading">
    <!-- 无权限页面 -->
    <div v-if="detailAuth === 'hide'">
      <no-auth v-if="noPermissionOrNoData === 1"></no-auth>
      <!-- 数据删除刷新页面显示暂无数据页面 -->
      <BaseListForNoData v-if="noPermissionOrNoData === 2" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
    </div>
    <!-- 因为下面有用到调用子组件的方法的，所以只能用v-show -->
    <div class="fault-library-detail-con" v-show="detailAuth === 'show'">
      <header-com :init-data="initData" class="fault-library-header" :description="headerTitle" :faultDescTitle="faultDescTitle" :query="query" @getData="getData" />
      <BaseTileLayoutTabBar
          v-if="taskLayout === 1"
          :bar-list="taskLayoutTabBarList"
          :now-item="leftActiveTab"
          @changeItem="tabBarChangeItem"
          @openLayoutModal="openBaseLayoutModal"
          :structure="2"
        ></BaseTileLayoutTabBar>
      <base-collapse class="task-detail-main-content" :hide-part-collapse="hidePartCollapse" :direction.sync="collapseDirection">
        <template slot='left'>
          <div class="task-detail-main-content-left" v-show="collapseDirection != 'left'">
            <BaseTileLayoutTabBar class="bg-fa" v-if="taskLayout === 2" :bar-list="taskLeftBarList" :now-item="leftActiveTab" :structure="2" @openLayoutModal="openBaseLayoutModal"></BaseTileLayoutTabBar>

              <fault-view ref="faultViewRef" :form-cell-count="formCellCount" :query="query" @headerTitle="setHeaderTitle"></fault-view>
          </div>
          <div class="collapse-left" v-show="collapseDirection == 'left'">{{$t('common.tabs.detail')}}</div>
        </template>
        

        <template slot="right">

          <!-- 故障对象和故障描述详情页面特有 -->
          <div
              class="task-detail-main-content-right"
              v-show="collapseDirection != 'right'"
              
              v-loading="rightTabBarLoading"
              >
              <BaseBarV3
              v-if="taskLayout == 2"
              :bar-list="tabBarList"
              :now-item="rightActiveTab"
              @changeItem="tabBarChangeItem"
              @upDateBarList="tabBarUpdateList"
              ></BaseBarV3>
            <div v-if="query.type !== 'solution'">
              <fault-right  ref="faultRightRef" :query="query" :rightActiveTab="rightActiveTab"/>

            </div>
            <div v-else>
              <fault-solute-right :query="query" ref="faultRightRef" :rightActiveTab="rightActiveTab"/>
            </div>
          </div>
          <div class="collapse-right" v-show="collapseDirection == 'right'">
              {{rightActiveTabItem[tabLabelKey]}}
            </div>
        </template>
      </base-collapse>

      <biz-layout-modal ref="bizLayoutModal" :columns="formCellCount" :biz-layout-type="baseLayout" @changeLayout="changeTaskDetailLayout"> </biz-layout-modal>
    </div>
  </section>
</template>

<script>
// api
import { checkFault } from '@src/api/Fault';

// header内容
import HeaderCom from '../components/FaultDetail/HeaderCom';
// 左边展示区域
import FaultView from '../components/FaultDetail/FaultView';
// 左边展示区域--(故障对象和故障描述类型的详情页面右侧)
import FaultRight from '../components/FaultDetail/FaultRight';
// 左边展示区域--(解决方案的详情页面右侧)
import FaultSoluteRight from '../components/FaultDetail/FaultSoluteRight';
import noAuth from '@src/modules/calendar/noAuth.vue';
import { toast } from '@src/util/platform';

import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue';
import { t } from '@src/locales';
import { useStateSystemViewLayout } from 'pub-bbx-utils'
import { BaseTabBarUsualEnum, StorageHttpParamsForTerminalType, StorageHttpParamsForModuleType } from '@src/component/common/BaseTabBar/enum'
import { getStorageForDetailTabbar, setStorageForDetailTabbar, getRichTextContent } from '@src/api/SystemApi'
import { cloneDeep } from '@src/util/type';
import BaseBarV3 from '@src/component/common/BaseTabBar/BaseTabBarV3.vue'
import { computedTabList } from '@src/util/tabBarUtils'

export default {
  // 故障详情
  name: 'FaultLibraryDetail',
  data() {
    return {
      collapse: true,
      loading: false,
      rightActiveName: '',
      faultDescTitle: '',
      detailAuth: '',
      noPermissionOrNoData: '',
      collapseDirection: '',
      taskLeftBarList: [],
      tabBarList:[],
      leftActiveTab: 'detail',
      rightActiveTab: '',
      tabPosition: '',
      rightActiveTabItem:{},
      taskLayoutTabBarList: [],
      baseLayout: 1,
      formCellCount: 1,
      tabLabelKey:BaseTabBarUsualEnum.TabBarListItemLabel,
    };
  },

  props: {
    query: {
      type: Object,
    },
    initData: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    HeaderCom,
    FaultView,
    FaultRight,
    FaultSoluteRight,
    noAuth,
    BaseTileLayoutTabBar,
    BaseBarV3
  },
  created() {
    // 折叠面板缓存
    let collapse = sessionStorage.getItem(`Fault_collapseDirection_${this.$route.query.id}`);
    let collapseDirection = sessionStorage.getItem(`Fault_collapseDirection_${this.$route.query.id}`);
    this.collapse = JSON.parse(collapse || 'true');
    this.collapseDirection = collapseDirection || '';
  },
  watch: {
    collapseDirection(newValue) {
      sessionStorage.setItem(`Fault_collapseDirection_${this.this.$route.query.id}`, newValue);
    },
    "taskLeftBarList": {
      handler() {
        this.taskLayoutTabBarList = cloneDeep([...this.taskLeftBarList,...this.tabBarList].filter(item => item.tabShow));
      },
      deep: true
    },
    "tabBarList": {
      handler() {
        this.taskLayoutTabBarList = cloneDeep([...this.taskLeftBarList,...this.tabBarList].filter(item => item.tabShow));
      },
      deep: true
    },
  },

  

  computed: {
    taskLayout() {
      return this.baseLayout
    },
    hidePartCollapse() {
      if(this.taskLayout === 1) return this.tabPosition === 'left' ? 'right' : 'left';
      return '';
    },
    headerTitle() {
      if (this.faultDescTitle) {
        return this.faultDescTitle;
      }

      return this.query.type === 'solution' ? this.$t('faultLibrary.detail.solution') : '';
    },
  },

  async mounted() {
    this.initLayoutData()

    this.fetchCheckFault();

    this.getData();
    await this.initRightTabBar()
  },

  methods: {
    tabBarUpdateList(list){
      const { TabBarCardInfoType, TabBarListItemKey:tabName, TabBarListItemShow:tabShow } = BaseTabBarUsualEnum;
      let list_ = list.map(item=>{
        return {
          cardId: item.type == TabBarCardInfoType ? item.id : item[tabName],
          checked: item[tabShow]
        }
      })
      let parasm_ = {
        equipment:StorageHttpParamsForTerminalType.PC,
        bizType:StorageHttpParamsForModuleType.Task,
        bizTypeId:this.query.id,
        cardList:list_
      }
      setStorageForDetailTabbar(parasm_)
    },
    tabBarChangeItem(item){
      console.log(194,item)
      let { TabBarListItemKey:tabName, TabBarListItemType:tabType, TabBarCardInfoType } = BaseTabBarUsualEnum;
      this.$refs.rightContent?.scrollTo(0, 0)
      this.tabPosition = item.position;
      if(this.taskLayout === 1 || item.position === 'left') {
        this.leftActiveTab = item[tabName];
      } 
      if(item.position === 'right') {
        this.rightActiveTab = item[tabName];
        this.rightActiveTabItem = item;
      }

    },
    async initRightTabBar(){
      if (this.taskLayout === 1) {
        this.tabPosition = 'left';
      }
      let taskLeftBarList = [
        { position: 'left', tabLabel:this.$t('common.tabs.detail'), tabName: 'detail', tabShow: true}, // 产品信息
      ]
        let barArr = this.query.type !== 'solution' ? [{tabName:'nextLevelMes', tabLabel:i18n.t('faultLibrary.detail.nextLevel'), tabShow:true,position: 'right' },
      {tabName:'task', tabLabel:i18n.t('common.base.task'), tabShow:true,position: 'right' },
      {tabName:'remark', tabLabel:i18n.t('common.base.comment'), tabShow:true,position: 'right' }] : [{tabName:'taskTableRef', tabLabel:i18n.t('faultLibrary.detail.faultOrderRecord'), tabShow:true,position: 'right' },{tabName:'remark', tabLabel:i18n.t('common.base.comment'), tabShow:true,position: 'right' }]

      // 读取缓存tabbar修改右栏tabbar配置
      try {
        let { TabBarListItemKey:tabName, TabBarListItemShow:tabShow} = BaseTabBarUsualEnum;
        let params = {
          equipment:StorageHttpParamsForTerminalType.PC,
          bizType:StorageHttpParamsForModuleType.Product,
          bizTypeId:`productType_${getUrlObj.id}`
        }
        // 获取tabbar用户行为缓存/*  */
        let storageList = await getStorageForDetailTabbar(params);
        if(storageList.status !== 0) {
          throw storageList.message
        }
        let storageList_ = storageList.data.map(item=>{
          const { cardId, checked} = item;
          return {
            [tabName]:cardId,
            [tabShow]:checked
          }
        })
        barArr = computedTabList(barArr, storageList_)
      } catch (error) {
        console.warn(error, 'error try catch getStorageForDetailTabbar');
      }
      this.leftActiveTab = taskLeftBarList[0].tabName;
      this.taskLeftBarList = taskLeftBarList;
      this.rightActiveTab = barArr[0].tabName;
      this.tabBarList = barArr;
    },
    getData() {
      let promisePort = [
        this.$refs.faultViewRef?.getPortPromise(this.query), // 左侧详细信息的接口
        this.$refs.faultRightRef?.getPortPromise(this.query), // 右侧列表数据接口
      ];
      this.loading = true;
      Promise.all(promisePort)
        .then(res => {
          this.$refs.faultViewRef.setData(res[0]);
          this.$refs.faultRightRef.setData(res[1]);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    setHeaderTitle(data) {
      this.faultDescTitle = data;
    },
    // 权限校验
    fetchCheckFault() {
      try {
        // type :1，故障， 2 解决方法
        let type = {
          solution: 2,
          description: 1,
          obj: 1,
        };
        checkFault({
          id: this.query.id,
          type: type[this.query.type],
        }).then(res => {
          const { success, data, message } = res;
          if (!success) return toast(message, 'error');
          // isShow 为false 的时候， type 1 为没有权限， type 2 为删除
          // true 有权限 显示详情页面 false 没权限 - 防止会先显示无权限页面在显示数据页面，所以数据转一下
          this.detailAuth = data?.isShow ? 'show' : 'hide';
          this.noPermissionOrNoData = data?.type;
        });
      } catch (err) {
        console.log('fetchCheckFault => err', err);
      }
    },
    openBaseLayoutModal() {
      this.$refs.bizLayoutModal.open();
    },
    changeTaskDetailLayout(type, columns) {
      this.leftActiveTab = 'detail' 
      this.baseLayout = type
      this.tabPosition = 'left'
      if(type === 2) {
        this.rightActiveTab = this.query.type !== 'solution' ?  'nextLevelMes' : 'taskTableRef'
      }
      this.formCellCount = columns * 1;
    },
    async initLayoutData(){
      const { getSystemViewLayout } = useStateSystemViewLayout()
      const count = await getSystemViewLayout()
      this.baseLayout = count.baseLayout || 2;
      this.formCellCount = count.formCellCount || 1;
    }
  },
};
</script>

<style lang="scss" scoped>
@import '../scss/FaultLibraryView';
.fault-library-detail-con {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.fault-library-contain {
  background: #ecf0f5 !important;
  display: flex;
  flex-flow: row !important;
  padding: 0 !important;

  ::v-deep .base-collapse-left {
    .el-tabs__active-bar {
      display: none;
    }
  }
  ::v-deep .base-collapse-right {
    .el-tabs__item {
      &.is-active {
        @include fontColor();
      }
    }
  }

  ::v-deep .el-tabs {
    display: flex;
    flex-direction: column;
    &__header {
      background: #fafafa;
      width: 100%;
      .el-tabs__item {
        font-weight: 400;

        color: $text-color-regular;
      }
    }
    &__nav-wrap {
      padding-left: 16px;
    }
    &__content {
      overflow: auto;
    }
  }
}
.bg-fa {
  background: #fff!important;
}
.task-detail-main-content {
  height: 100%;
}
::v-deep .base-collapse-left,::v-deep .base-collapse-left {
  overflow:auto!important;
  position:static!important;
}
</style>
